#coding=utf-8
import datetime
import os

from loguru import logger
from playwright.sync_api import sync_playwright
import traceback

import xiaohongshu.xhs_common as xhs_common

def group_by_period(job_list):
    job_group = {}
    period_list = list(set(map(lambda x: x['period'], job_list)))
    for period in period_list:
        filter_list = list(filter(lambda x: x['period'] == period, job_list))
        job_group[period] = filter_list
    return job_group

def xhs_main(host, account_list):
    try:
        store_id_list = list(set(map(lambda x: x['storeId'], account_list)))
        logger.info('正在运行小红书RPA...')
        with sync_playwright() as playwright:
            xhs_func = xhs_common.Xiao_Hong_Shu(host, playwright, 'haiwangou-key')
            for store_id in store_id_list:
                for i in range(3):
                    try:
                        store_job_list = list(filter(lambda x: x['storeId'] == store_id, account_list))
                        logger.info(f"正在下载【{store_job_list[0]['platformStoreName']}】账单")
                        xhs_func.login(store_job_list[0], 2)
                        # 按照周期分组，按每个周期循环运行，每跑完一个周期上传一次
                        job_group = group_by_period(store_job_list)
                        for period, job_list in job_group.items():
                            param_list = []
                            file_list = []
                            logger.info(f'正在下载周期【{period}】的账单...')
                            for item in job_list:
                                start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                if item['accountType'] == '订单销售':
                                    logger.info('开始下载【订单销售】...')
                                    fund_flow_file = xhs_func.download_bill_and_refund(item, period)
                                    if fund_flow_file is not None:
                                        file_list.append(fund_flow_file)
                                        dir_path, file_name = os.path.split(fund_flow_file)
                                        param_list.append({'orderType': '订单销售', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                    else:
                                        param_list.append({'orderType': '订单销售', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                if item['accountType'] == '订单退款':
                                    logger.info('开始下载【订单退款】...')
                                    fund_flow_file = xhs_func.download_bill_and_refund(item, period)
                                    if fund_flow_file is not None:
                                        file_list.append(fund_flow_file)
                                        dir_path, file_name = os.path.split(fund_flow_file)
                                        param_list.append({'orderType': '订单退款', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                    else:
                                        param_list.append({'orderType': '订单退款', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                if item['accountType'] == '货款明细':
                                    logger.info('开始下载【货款明细】...')
                                    bill_file = xhs_func.download_sale_detail(item, period)
                                    if bill_file is not None:
                                        file_list.append(bill_file)
                                        dir_path, file_name = os.path.split(bill_file)
                                        param_list.append({'orderType': '货款明细', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                    else:
                                        param_list.append({'orderType': '货款明细', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                if item['accountType'] == '订单结算明细':
                                    logger.info('开始下载【订单结算明细】...')
                                    bill_file = xhs_func.download_order_detail(item, period)
                                    if bill_file is not None:
                                        file_list.append(bill_file)
                                        dir_path, file_name = os.path.split(bill_file)
                                        param_list.append({'orderType': '订单结算明细', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                    else:
                                        param_list.append({'orderType': '订单结算明细', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                if item['accountType'] == '微信明细':
                                    logger.info('开始下载【微信明细】...')
                                    bill_file = xhs_func.download_wechat_detail(item, period)
                                    if bill_file is not None:
                                        file_list.append(bill_file)
                                        dir_path, file_name = os.path.split(bill_file)
                                        param_list.append({'orderType': '微信明细', 'fileName': file_name, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                    else:
                                        param_list.append({'orderType': '微信明细', 'fileName': '无', 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                if item['accountType'] == '订单销售总数':
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_count = xhs_func.get_bill_and_refund_count(period)
                                    param_list.append({'orderType': '订单销售总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                if item['accountType'] == '订单退款总数':
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_count = xhs_func.get_bill_and_refund_count(period)
                                    param_list.append({'orderType': '订单退款总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                if item['accountType'] == '货款明细总数':
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_count = xhs_func.get_sale_detail_count(period)
                                    param_list.append({'orderType': '货款明细总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                if item['accountType'] == '微信明细总数':
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_count = xhs_func.get_wechat_detail_count(period)
                                    param_list.append({'orderType': '微信明细总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                                if item['accountType'] == '订单结算明细总数':
                                    start_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
                                    bill_count = xhs_func.get_order_detail_count(period)
                                    param_list.append({'orderType': '订单结算明细总数', 'fileName': bill_count, 'period': period, 'logId': item['logId'], 'startTime': start_time})
                            if len(param_list) > 0:
                                # 编码字符串
                                coding_param = xhs_func.encode_param(param_list)
                                # 上传文件
                                uri = "api/v1/xhsBill/xhsBillRPAImport/{}".format(item['storeCode'])
                                xhs_func.upload_file(uri, coding_param, file_list)
                        xhs_func.close()
                        break
                    except:
                        logger.info(traceback.format_exc())
                        xhs_func.close()
    except:
        logger.info(traceback.format_exc())